package org.example.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

/**
 * 要求：使用JDBC在tedu库下的user表中插入1条表记录;
 * 注册功能：
 *    用户在页面里面输入
 */
public class Demo01JDBC {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        /*
            1.加载数据库驱动;
            2.创建数据库连接对象;
            3.创建SQL语句的执行对象;
            4.执行SQL语句;
            5.获取SQL语句的执行结果;
            6.断开数据库连接;
         */
        //1.加载数据库的驱动;
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.创建数据库连接对象;
        Connection connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/tedu?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true",
                "root",
                "root"
        );
        //3.创建SQL语句的执行对象;
        Statement statement = connection.createStatement();
        //接收用户输入;
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String username = scanner.nextLine();
        System.out.println("请输入密码：");
        String password = scanner.nextLine();
        System.out.println("请输入昵称：");
        String nickname = scanner.nextLine();
        System.out.println("请输入年龄：");
        int age = scanner.nextInt();

        //4.执行SQL语句：executeUpdate()-执行写操作;executeQuery()-执行查询操作;
        //"+变量名+"   作用：把外部变量的值嵌入到SQL语句中;
        statement.executeUpdate("INSERT INTO user(username, password, nickname, age) VALUES ('"+username+"','"+ password+"','"+nickname+"',"+age+")");
        System.out.println("数据插入成功;");
        //5.断开数据库连接;
        connection.close();
    }
}
